﻿<%@ page language="java" contentType="text/html; charset=UTF-8"   pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ include file="international.jsp" %> 
<jsp:useBean id="trackerService" class="com.brother.service.TrackerService"></jsp:useBean>
<jsp:useBean id="carmodelService" class="com.brother.service.CarModelService"></jsp:useBean>
<jsp:useBean id="userService" class="com.brother.service.UserService"></jsp:useBean>

<jsp:useBean id="postTracker" class="com.brother.model.Tracker"></jsp:useBean>
<jsp:setProperty property="*" name="postTracker"/>
<jsp:useBean id="postUser" class="com.brother.model.Customer"></jsp:useBean>
<jsp:setProperty property="*" name="postUser"/>
<%
com.brother.model.Customer user = (com.brother.model.Customer)session.getAttribute(com.brother.Constants.LOGIN_SESSTION_NAME);
com.brother.model.Customer trackerUser = null;
if(user == null || user.getUserid() == 0 || !user.isAdmin())
	return;
String trackerId = request.getParameter("trackerid") == null ?"":request.getParameter("trackerid").trim();
String carModelId = request.getParameter("carModelId") == null ?"":request.getParameter("carModelId").trim();

com.brother.model.Tracker tracker = null; 

boolean alreadyExistTracker = false;
boolean alreadyExistIMEI = false;
boolean alreadyExistUser = false;


java.util.List<com.brother.model.CarModel> carModels = carmodelService.getAllCarModels();
String action = request.getParameter("action");
if(action != null && action.equalsIgnoreCase("submitted")){
	
	boolean actionSuc = false;
	boolean toAction = false;
	if(postTracker.getTrackerName().length() > 0 &&
			postTracker.getUserTrackerId().length() > 0&&
			postUser.getName().length() > 0 ){
		alreadyExistTracker = (trackerService.getTrackerByFieldName("trackerName",postTracker.getTrackerName()) != null);
		alreadyExistIMEI = (trackerService.getTrackerByFieldName("userTrackerId",postTracker.getUserTrackerId()) != null);
		alreadyExistUser = (userService.GetUserByUserFieldName("name", postUser.getName()) != null);
		
		toAction = true;
	}else{
		tracker = postTracker;
		trackerUser = postUser;
	}
	if(trackerId.length() == 0 && toAction && !alreadyExistTracker && !alreadyExistIMEI){ // 添加tracker
		    postTracker.setUserTrackerId(postTracker.getUserTrackerId().trim());
			trackerService.addTracker(postTracker);
			
			actionSuc = true;
		
	}else if(toAction){  //  修改tracker
		postTracker.setUserTrackerId(postTracker.getUserTrackerId().trim());
		trackerService.updateTracker(postTracker);
		actionSuc = true;
	}
	if(actionSuc)
		response.sendRedirect("trackerList.jsp");
}else{
	if(trackerId!= null && !trackerId.isEmpty()){
		tracker = trackerService.getTrackerByFieldName("trackerid",trackerId);
		trackerUser = userService.GetUserByUserId(tracker.getUserid());
	}
}


%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title><fmt:message key="manage.tracker.modify"/> - <fmt:message key="company.name"/></title>
<meta name="description" content="" />
<link rel="stylesheet" type="text/css" media="all" href="style.css" />
<link rel="stylesheet" type="text/css" href="css/ext-all.css" />
<link rel="stylesheet" type="text/css" href="css/grid-examples.css" />

    <script type="text/javascript" src="js/ext-base.js"></script>
    <script type="text/javascript" src="js/ext-all.js"></script>
    <script type="text/javascript" src="js/search.js"></script>
    
  <script type='text/javascript' src='dwr/engine.js'> </script>
  <script type='text/javascript' src='dwr/util.js'> </script>
  <script type='text/javascript' src='dwr/interface/TrackerService.js'> </script>
    <script type='text/javascript' src='dwr/interface/UserService.js'> </script>
  <script type="text/javascript" src='js/realtime.js'></script>  
    
  <style type="text/css">
<!--
.STYLE1 {color: #FFFFFF}
.STYLE2 {color: #FF0000}
body{
background-color: #FFFFFF;
}
-->
  </style>
</head>
<body >
<div id="msg" name="msg" style="background-color:#D4DF55; position:absolute; z-index:11; left: 10px; top: 61px; display:inline"></div>
<script>
var search_select_user='<fmt:message key="search.select.user"/>';
var search_select_tracker='<fmt:message key="search.select.tracker"/>';
Ext.onReady(function(){
	//document.getElementById('password').value = '';

	
	
});

       function Point(iX, iY){ 
          this.x = iX; 
          this.y = iY; 
       } 
 function fGetXY(obj){ 
           var oTmp = obj;     
           if(!oTmp||(typeof(oTmp.offsetLeft) == "undefined") 
               ||(typeof(oTmp.offsetTop) == "undefined") 
               ||!oTmp.tagName){ 
                return null; 
           } 
           var pt = new Point(0,0);   
           do{ 
      pt.x += oTmp.offsetLeft; 
      pt.y += oTmp.offsetTop; 
      //alert(oTmp.parentNode.tagName);
      oTmp = oTmp.parentNode; 
  } while(oTmp.tagName!="BODY"); 
  return pt; 
       } 
       
	   var gMsgTop = 0; //fGetXY(document.getElementById("tmp_pos")).y;
function show_tip(msg)
{
	if (gMsgTop == 0)
	{
		gMsgTop = fGetXY(document.getElementById("tmp_pos")).y + 5;
		document.getElementById("msg").style.top = gMsgTop;
		document.getElementById("msg").style.display = "inline";
		// alert(document.getElementById("msg").style.offsetTop);
	}
	
	document.getElementById("msg").innerHTML = msg;
}

var trackerIconsWin = null;
function showTrackerIcons(){
	var top = document.body.scrollTop;
	var url = "trackerIcons.jsp";
	var config = {
		    url: url,
		    params: {}, // or a URL encoded string
		    callback: function(g1,g2, res){ var text = res.responseText; if(text.indexOf('loginPage.jsp') > -1){ location.href = './login.jsp'; } },
		    discardUrl: false,
		    nocache: false,
		    text: 'Loading...',
		    timeout: 30,
		    scripts: false
		};
	if(trackerIconsWin == null){
		trackerIconsWin = new Ext.Window({resizable:false,width:400,bodyCssClass:'panel_whitebg', height:300, closeAction:'hide',title:'<fmt:message key="tracker.model.choose"/>', modal:true, applyTo:'iconsWindow', cls:'panel_whitebg'});
		trackerIconsWin.load(config);
		trackerIconsWin.setPosition(document.body.clientWidth / 2 -  trackerIconsWin.getWidth() / 2, top + 50);
	}
	trackerIconsWin.show();
}

function setModel(model){
	if(trackerIconsWin != null){
		trackerIconsWin.hide();
	}
	document.getElementById('modelName').value = model;
	document.getElementById('modelImage').src = getOnlineIcon({model:model});
}

var trackerNameRequired = '<fmt:message key="tracker.name.required"/>';
var IMEIRequired = '<fmt:message key="tracker.imei.required"/>';
var UserIDRequired = '<fmt:message key="user.userid.required"/>';
var PasswordRequired = '<fmt:message key="user.password.required"/>';
var overwritePassword = '<fmt:message key="user.password.overwrite.warning"/>';

function checkSubmit(){
	
	var trackerName = document.getElementById("trackerName").value;
	if(trackerName.length == 0){
		//alert(trackerNameRequired);
		Ext.MessageBox.show({
            title: '',
            msg: trackerNameRequired,
            buttons: Ext.MessageBox.OK,
            icon: Ext.MessageBox.WARNING
        });
		return false;
	}
	
	if(isExistsIMEI){
		//alert(ExistsIMEI);
		Ext.MessageBox.show({
            title: '',
            msg: ExistsIMEI,
            buttons: Ext.MessageBox.OK,
            icon: Ext.MessageBox.WARNING
        });
		return false;
	}
	
	var userTrackerId = document.getElementById("userTrackerId").value;
	if(userTrackerId.length == 0){
		//alert(IMEIRequired);
		Ext.MessageBox.show({
            title: '',
            msg: IMEIRequired,
            buttons: Ext.MessageBox.OK,
            icon: Ext.MessageBox.WARNING
        });
		return false;
	}
	if(isExistsTrackerName){
		//alert(ExistsTrackerName);
		Ext.MessageBox.show({
            title: '',
            msg: ExistsTrackerName,
            buttons: Ext.MessageBox.OK,
            icon: Ext.MessageBox.WARNING
        });
		return false;
	}
	
	var userID = document.getElementById("userAutocomplete").value;
	if(userID.indexOf("Select") > -1){
		userID = "";
	}
	if(userID.length == 0){
		//alert(UserIDRequired);
		Ext.MessageBox.show({
            title: '',
            msg: UserIDRequired,
            buttons: Ext.MessageBox.OK,
            icon: Ext.MessageBox.WARNING
        });
		return false;
	}
	var password = "";//document.getElementById("password").value;
	if(password.length == 0){
		//alert(PasswordRequired);
		//return false;
	}else if(!confirm(overwritePassword)){
		document.getElementById("password").focus();
		return false;
	}

	if(isExistsUserID){
		//alert(ExistsUserID);
		Ext.MessageBox.show({
            title: '',
            msg: ExistsUserID,
            buttons: Ext.MessageBox.OK,
            icon: Ext.MessageBox.WARNING
        });
		return false;
	}
	
	return true;
}

function onUserSelect(user){
	document.getElementById("userid").value = user.userid;
	onUserInput(user.name);
}


function onUserInput(name){
	UserService.GetUserByUserFieldName('name',name, function(model){
		if(model != null){
			
			document.getElementById("userid").value = model.userid;
			try{
				document.getElementById("realNametext").innerHTML = model.realName;
			}catch(e){
				document.getElementById("realNametext").innerText = model.realName;
			}
			document.getElementById("realNameField").value = model.realName;
			
			return;
			
			if(model.gender == 'Male'){
				document.getElementById("maleGender").checked = true;
				document.getElementById("femaleGender").checked = false;
			}else{
				document.getElementById("maleGender").checked = false;
				document.getElementById("femaleGender").checked = true;
			}
			document.getElementById("companyName").value = model.companyName;
			document.getElementById("email").value = model.email;
			document.getElementById("address").value = model.address;
			document.getElementById("country").value = model.country;
			document.getElementById("mobile").value = model.mobile;
			document.getElementById("fax").value = model.fax;
			
			document.getElementById("phoneNumber").value = model.phoneNumber;
			document.getElementById("description").value = model.description;

			//setTimeout("document.getElementById('password').value = ''", 1000);
			
		}else{
			
		}
	});
	
}

var ExistsUserID = 'User ID exits';
var isExistsUserID = false;
function checkUserExist(userid){
	UserService.GetUserByUserId(userid, function(model){
		if(model != null){
			//isExistsUserID = true;
		}else{
			isExistsUserID = false;
		}
	});
}

var isExistsTrackerName = false;
var ExistsTrackerName = 'Name already exits!';
function checkTrackerNameExist(trackerName){
	TrackerService.getTrackerByFieldName('trackername',trackerName ,function(model){
		//console.log(arguments);
		if(model != null){
			isExistsTrackerName = true;
		}else{
			isExistsTrackerName = false;
		}
	});
}

var isExistsIMEI = false;
var ExistsIMEI = '<fmt:message key="manage.tracker.name.exists"/>';
function checkIMEIExist(imei){
	TrackerService.getTrackerByFieldName('userTrackerId',imei ,function(model){
		if(model != null){
			isExistsIMEI = true;
		}else{
			isExistsIMEI = false;
		}
	});
}

<%if(trackerId.length() == 0){ %>
var edit_tracker_title = '<fmt:message key="manage.tracker.add"/>';
<%}else{ %>
var edit_tracker_title = '<fmt:message key="manage.tracker.modify"/>';
<%} %>

Ext.onReady(function(){
	top.ajustProducts(edit_tracker_title, 540, 540);
});

</script>
<div id="iconsWindow" style="z-index:200"></div>
<table  width="100%" height="100%" border="0" cellpadding="0" cellspacing="0">



<tr valign="top">
	<td valign="top" align="left" style="padding-left:8px; padding-right:8px;">

<table width="100%" align="left" >
	<tr valign="top">
		<td valign="top" align="left" >
		
		<form action="gps_editproduct.jsp" method="post" onSubmit="return checkSubmit();">
						<table align="left"   border="1" class="tableBorder1" cellpadding="5" width="500">
				  
				  <%if(alreadyExistTracker){ %>
				  
				  <tr>
				  <td colspan="2"><SPAN style="color:red;"><fmt:message key="tracker.already.exist"/></SPAN></td>
				</tr>
				  <%} %>
				<%if(alreadyExistIMEI){ %>
				  <tr>
				  <td colspan="2"><SPAN style="color:red;"><fmt:message key="tracker.imei.already.exist"/></SPAN></td>
				</tr>
				  <%} %>		  
				  
				  
				<tr valign="top">

				  <th width="180" align="right" valign="top"><fmt:message key="tracker.name"/>:</th>
				  <td width="300"><input name="trackerName" onChange="checkTrackerNameExist(this.value);" id="trackerName" type="text" value="<%=tracker==null?"":tracker.getTrackerName()%>" size="30" />
				    <span class="STYLE2">*</span></td>
				</tr>
				<tr>
					<th align="right"><fmt:message key="tracker.model"/>:</th>
					<td>
					<input type="hidden" name="modelName" id="modelName" value="<%=tracker!=null?(tracker.getModelName() != null ?  tracker.getModelName() : ""):""%>"/>
					<img src="" id="modelImage" alt="" />
					<script type="text/javascript">
					document.getElementById('modelImage').src = getOnlineIcon({model:'<%=tracker!=null?(tracker.getModelName() != null ?  tracker.getModelName() : ""):""%>'});
					</script>
					<input type="button" onclick="showTrackerIcons();" value="<fmt:message key="tracker.model.choose"/>"/>
					</td>
				</tr>
				<tr>

					<th align="right"><fmt:message key="tracker.protocol"/>:</th>
					<td><select name="carmodelId" id="carmodelId">
					<option value="7"><fmt:message key="tracker.protocol.default"/></option>
					<option value="8" <%if((tracker!=null?(tracker.getCarmodelId().equals("8")):false)){%>selected<%}%>><fmt:message key="tracker.protocol.TL201"/></option>
					<option value="9" <%if((tracker!=null?(tracker.getCarmodelId().equals("9")):false)){%>selected<%}%>><fmt:message key="tracker.protocol.TL108"/></option>
					<option value="10" <%if((tracker!=null?(tracker.getCarmodelId().equals("10")):false)){%>selected<%}%>>EV06</option>
					</select></td>
				</tr>
				<tr>

					<th align="right"><fmt:message key="tracker.id"/>:</th>
					<td><input name="userTrackerId"  onchange="checkIMEIExist(this.value);"  id="userTrackerId" type="text" value="<%=tracker==null?"":tracker.getUserTrackerId()%>" size="30">
				    <span class="STYLE2">*</span></td>
				</tr>
				<tr>
				  <th align="right"><fmt:message key="user.id"/>: </th>
				  <td nowrap="nowrap"><table style="border-collapse:collapse;" cellpadding="0" cellspacing="0" border="0">
				  <tr><td style="border-collapse:collapse;border:0px;padding:0px 0px 0px 0px"><input onblur="onUserInput(this.value)" name="name" readonly="readonly" onChange="onUserInput(this.value)" type="text" value="<%=tracker==null?(""):trackerUser.getName()%>" id="userAutocomplete" size="30"></td>
				  <td style="border-collapse:collapse;border:0px;padding:0px 0px 0px 0px"><span class="STYLE2">*</span></td></tr></table>
			      </td>
				  </tr>
				  <tr>
				  <th align="right"><fmt:message key="user.username"/>: </th>
				  <td nowrap="nowrap"><input type="hidden" id="realNameField" name="realName" value="<%=tracker==null?(""):trackerUser.getRealName()%>"/><div id="realNametext"><%=tracker==null?(""):trackerUser.getRealName()%></div></td>
				  </tr>
				<tr>
				  <th align="right"><fmt:message key="tracker.receive.mail"/>: </th>
				  <td><input type="checkbox"  <%=tracker==null?"":(tracker.isMailEnabled()? "checked":"")%>  name="mailEnabled" value="true">
				    <fmt:message key="tracker.receive.mail.description"/> </td>
				  </tr>
				<tr>
				  <th align="right"><fmt:message key="tracker.driver.id"/>: </th>
				  <td><input name="driverID" type="text" value="<%=tracker==null?"":tracker.getDriverID()%>" size="30"></td>
				  </tr>
				<tr>
				  <th align="right"><fmt:message key="tracker.driver.name"/>: </th>
				  <td><input name="driverName" type="text" value="<%=tracker==null?"":tracker.getDriverName()%>" size="30"></td>
				  </tr>
				<tr>
				  <th align="right"><fmt:message key="tracker.driver.mobile"/>: </th>
				  <td><input name="driverMobile" type="text" value="<%=tracker==null?"":tracker.getDriverMobile()%>" size="30"></td>
				  </tr>
				<tr>
				  <th align="right"><fmt:message key="tracker.remark"/>:</th>
				  <td>
				  						<input type="hidden" name="userid" id="userid" value="<%=tracker==null?user.getUserid():tracker.getUserid()%>" />
						<input type="hidden" name="action" value="submitted" />
						<input type="hidden" name="trackerid" value="<%=tracker==null?"":tracker.getTrackerid()%>" />
				  
				  <textarea name="remark"  cols="50"  rows="8" id="remark"><%=tracker==null?"":(tracker.getRemark() == null ? "":tracker.getRemark())%></textarea></td>
				  </tr>
				
			</table>
			
			</form>
		
		</td>
	</tr>
	<tr>
				
					<td align="left" style="padding-left:190px">
					<table border=0 cellpadding="0" cellspacing="3">
					<tr><td><span id="submitBtm"></span></td><td><span id="cancelBtm"></span></td></tr>
					</table>
						
						<script>
				Ext.onReady(function(){
					 var button = new Ext.Button({renderTo:'submitBtm',type:'button', 
						text:'<%if(trackerId.length() == 0){ %><fmt:message key="manage.add.submit"/><%}else{ %><fmt:message key="manage.modify"/><%} %>',split: false,width:100,
						enableToggle:false});
						
						button.on('click',function(){
							if(!checkSubmit()){
								return;
							}
							document.forms[0].submit();
						});

						button = new Ext.Button({renderTo:'cancelBtm',type:'button', 
							text:'<fmt:message key="form.cancel"/>',split: false,width:100,
							enableToggle:false});

							button.on('click',function(){
								location.href='trackerList.jsp';
							});
						});		
							 
				
				</script>
						</td>
				</tr>
</table>

	</td>

</tr>


</table>

</body>
</html>
<%
com.brother.database.DataBase.closeThreadConnection();
%>